package com.sdx.console.crm.service;

import com.alibaba.fastjson.JSONObject;
import com.ibeetl.admin.core.util.DateUtil;
import com.sdx.console.crm.entity.CrmSession;
import com.sdx.console.customer.entity.CustomerInfo;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.db.KeyHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName CrmSessionService
 * @Description: 会话
 * @author: tanbaocai
 * @date: 2019/7/24 14:50
 */
@Service
public class CrmSessionService {

	@Resource
	private SQLManager sqlManager;

	public void closeSession(Integer sessionId) {
		CrmSession crmSession = new CrmSession();
		crmSession.setSessionId(sessionId);
		crmSession.setSessionStatus(4);
		crmSession.setCloseTime(new Date());
		sqlManager.updateTemplateById(crmSession);
	}

	/**
	 * 新增会话 并返回主键
	 * @param json
	 * @param userId
	 * @return
	 */
	public int insertSession(JSONObject json,Integer userId,CustomerInfo customerInfo,Integer tenantId){

		CrmSession crmSession = new CrmSession();
		crmSession.setAppId(json.getString("appId"));
		crmSession.setCustomerId(json.getString("customerId"));
		if(customerInfo!=null){
			crmSession.setPhone(customerInfo.getPhone());
		}
		crmSession.setSourceType(json.getIntValue("sourceType"));
		crmSession.setAppId(json.getString("appId"));
		crmSession.setOpenId(json.getString("openid"));
		crmSession.setUserId(userId);
		crmSession.setCreateTime(new Date());
		crmSession.setCreateDate(DateUtil.now());
		crmSession.setLastMessageType(1);
		crmSession.setLastMessageTime(new Date());
		crmSession.setSessionStatus(1);

		KeyHolder keyHolder = new KeyHolder();
		sqlManager.insert(CrmSession.class,crmSession,keyHolder);
		int key = Integer.parseInt(keyHolder.getKey().toString());

		return key;
	}

	public CrmSession getCrmSessionById(Integer sessionId){
		CrmSession crmSession = new CrmSession();
		crmSession.setSessionId(sessionId);
		return sqlManager.templateOne(crmSession);
	}

	public void sendUpdate(Integer sessionId,Integer messageType){
		CrmSession crmSession = new CrmSession();
		crmSession.setSessionId(sessionId);
		crmSession.setLastMessageType(messageType);
		crmSession.setCloseTime(new Date());
		sqlManager.updateTemplateById(crmSession);
	}
}
